package main
{
	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.utils.setTimeout;
	import flash.media.SoundMixer;
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.messaging.events.*;
	import mx.messaging.messages.*;
	/**
	 * Klasse zum verwalten von Login, Spielerstellung, Sound
	 * @author 3KP
	 * 
	 */
	public class GameControl
	{
		public static var table:RemoteTable;
		private static var app : Object = Application.application;
		private static var appF : Object = Application.application.facade;
		private static var appE : Object = Application.application.pokerEngine;
		public static var seatPos:int = -1;
		[Bindable]
		public static var myUserlist:ArrayCollection;
		[Bindable]
		public static var myPlayerlist:ArrayCollection;
		public static var user:User;
		private static var message:RemoteMessage;
		public static var sound:Boolean =true;
		public static var replayCollection:ArrayCollection;
		[Bindable]
		public static var replayCollectionDefined: ArrayCollection =new ArrayCollection();
		/**
		 * Consumer userlist 
		 * @param event
		 * 
		 */		
		public static function userlistHandler(event:MessageEvent) : void {
			myUserlist = event.message.body as ArrayCollection;
		} 
		
		
		/**
		 * liefert User zurück 
		 * @return 
		 * 
		 */		
		public static function getUser():User{
			return user;
		}
		
		/**
		 * Consumer playerlist 
		 * prueft Playerlist setzt gamemaster und statustext
		 * @param event
		 * 
		 */		
		public static function playerlistHandler(event:MessageEvent) : void {
			myPlayerlist = event.message.body as ArrayCollection;
			if(!myPlayerlist.contains(user.name)){
				// wenn noch nicht in Playerlist
				app.infoPregameLabel.text="Drücken Sie auf bereit, wenn sie spielen wollen."
			} else if(myPlayerlist[0] == user.name){
				// wenn Gamemaster
				app.spielstartOptions.visible=true;
				app.infoPregameLabel.text="Bitte setzen Sie die gewünschten Werte für Small Blind, Big Blind und Stackgröße und starten sie das Spiel wenn alle Spieler bereit sind.";
			} else {
				//wenn in playerlist aber kein Gamemaster
				app.spielstartOptions.visible=false;
				app.infoPregameLabel.text="Bitte warten Sie bis der Gamemaster das Spiel startet."
			}
			
			if (myPlayerlist.length>1){
				// ab 2 Spieler Start Button aktivieren
				app.gameStartButton.enabled=true;
			} else app.gameStartButton.enabled=false;
			
			
		}
		
		/**
		 * Producer GameState 
		 * fuer pregame
		 */		
		private static function pregame():void{
			var message:AsyncMessage = new AsyncMessage();
			message.body = new Object();
			message.body.gameState = "1";
			app.producerGameState.send(message);
		}
		
		/**
		 * Producer GameState 
		 * fuer game
		 */	
		private static function game():void{
			var message:AsyncMessage = new AsyncMessage();
			message.body = new Object();
			message.body.gameState = "2";
			app.producerGameState.send(message);
		}
		
		/**
		 * Consumer chat 
		 * gibt Chat Nachrichten an
		 * @param event
		 * 
		 */		
		public static function chatHandler(event:MessageEvent):void {
			
			app.ta.text = app.ta.text+"\n"+String(event.message.body.uName) + ":  " + 
				String(event.message.body.uInput);
			setTimeout(scroll, 500);
			
		}
		
		/**
		 * Consumer gameState 
		 * aendert gameState
		 * @param event
		 * 
		 */		
		public static function gameStateHandler(event:MessageEvent):void {
			app.currentState="pregame";
			if(String(event.message.body.gameState)== "1"){
				app.currentState="pregame";
			} else if (String(event.message.body.gameState)== "2"){
				app.currentState="game";
			}
		}
		
		/**
		 * Button Register Handler
		 * prueft username und registriert beim Server
		 */		
		public static function register_clickHandler():void
		{
			if(app.name1.text.length<2) {
				app.loginText.text="Der Username muss mindestens 3 Zeichen lang sein."
			} else if(app.name1.text.length>8){
				app.loginText.text="Der Username darf maximal 8 Zeichen lang sein."
			} else {
				app.makeUser.token = app.facade.makeSomeUsers(app.name1.text,app.password.text)
			}
		}
		
		/**
		 * Button Login Handler
		 * fragt password beim server ab 
		 */		
		public static function login_clickHandler():void
		{
			app.passworttestResult.token = app.facade.passworttest(app.name1.text,app.password.text);			
		}
		
		/**
		 * berechnet seat Postion fuer Spieler 
		 * 
		 */		
		public static function calcSeatPos():void{
			var counter:int = 0;
			for each(var a:String in myPlayerlist){
				if(a == user.name){
					seatPos = counter;
					break;
				}
				counter++;
			}
		}
		
		/**
		 * schreibt Stats fuer aktuellen Spieler 
		 * 
		 */		
		public static function writeStats():void{
			app.stats.text="Statistik fuer Spieler "+user.name+": \nGespielte Spiele: "+ user.games_played +"\nGewonnene Spiele: " + user.games_won;
		}
		
		/**
		 * Consumer table
		 * setzt gamestate auf game wenn ein Tisch empfangen wird, ruft drawTable auf und
		 * setzt gamestate auf pregame wenn spiel zu Ende
		 * @param event
		 * 
		 */		
		public static function tableHandler(event:MessageEvent):void{
			
			table = event.message.body as RemoteTable;
			PokerControl.rT =table;
			if(table!= null) app.currentState="game";
			if(table.activePlayerIndex == 5){
				
				app.currentState="pregame";
				
				app.getUserResult.token = app.facade.getUser(user.name);
			}
			RemoteTable.drawTable(table);	
		}
		
		/**
		 * Consumer message
		 * Schreibt dealer Text und ruft methde zum abspielen von sounds auf 
		 * @param event
		 * 
		 */		
		public static function messageHandler(event:MessageEvent):void{
			message = event.message.body as RemoteMessage;
			if(app.dealerT.selected){
				app.ta.text= app.ta.text +"\n" +message.text;
				
				setTimeout(scroll, 500);
			}
			playSound(message.sound);
		}
		
		/**
		 * Autoscroll fuer Chatfenster 
		 * 
		 */		
		private static function scroll():void{
			app.ta.verticalScrollPosition=(Math.floor(app.ta.contentHeight) - app.ta.height);
		}
		
		/**
		 * spielt Sound ab 
		 * @param sndSource
		 * 
		 */		
		public static function playSound(sndSource:String):void{
			if(sound){
				var meinSound:Sound = new Sound();
				SoundMixer.stopAll();
				meinSound.load(new URLRequest("main/snd/"+sndSource));
				meinSound.play(0,1,null);
			}
		}
		
		/**
		 * Button Mute Handler 
		 * 
		 */		
		public static function mute():void{
			if(sound){
				sound =false;
				appE.mute.label="Unmute";
			}  else {
				sound =true;
				appE.mute.label="Mute";
			}
			
		}
		
		/**
		 * Wird aufgerufen nach Passwordtest 
		 * @return 
		 * 
		 */		
		public static function passwordTest() {
			if(app.passworttestResult.lastResult){
				// bei Erfolg
				app.consumerTable.subscribe();
				app.consumerGameState.subscribe();
				app.consumerMessage.subscribe()
				app.currentState='pregame'; 
				app.getUserResult.token = app.facade.getUser(app.name1.text);
				app.facade.sendUserAndPlayersList();
				app.password.text="";
				app.loginText.text="";
			} else {
				// bei Misserfolg
				app.loginText.text="Username oder Passwort falsch!"
			}
		}
		
		/**
		 * Producer Chat 
		 * verschickt Chatnachrichten 
		 */		
		public static function sendMessage():void {
			var message:AsyncMessage = new AsyncMessage();
			message.body = new Object();
			message.body.uName = user.name;
			message.body.uInput = app.input.text;
			message.body.theCollection = ['b','a',3,new Date()];
			app.producerChat.send(message);
			app.input.text="";
			
		}
		
		/**
		 * Button Start Handler 
		 * startet das Spiel
		 */		
		public static function gameStart():void{
			
			game();
			app.facade.deleteTable();
			app.facade.createTable(parseInt(app.smallBlind.text),parseInt(app.bigBlind.text),parseInt(app.stack.text));
		}
		
		/**
		 * ueberprueft Eingabe fuer Spielparameter 
		 * @param id
		 * 
		 */		
		public static function checkValue(id:String):void{
			var sB:int = parseInt(app.smallBlind.text);
			var bB:int = parseInt(app.bigBlind.text);
			var st:int = parseInt(app.stack.text);
			if(id == "smallBlind"){
				if(sB > 1000) app.smallBlind.text="1000";
				if(sB<=0) app.smallBlind.text="1";
				if(sB>bB) app.smallBlind.text=app.bigBlind.text;
			} else if(id == "bigBlind"){
				if(bB > 2000) app.bigBlind.text="2000";
				if(bB<sB) app.bigBlind.text=app.smallBlind.text;
				if(bB>st) app.bigBlind.text=app.stack.text;
			} else {
				if(st< bB) app.stack.text=app.bigBlind.text;
				if(st > 100000) app.stack.text="100000";
			}
		}
		
		/**
		 * Schreibt ReplayCollection in ReplayCollectionDefined
		 * fuer anzeige im DataGrid 
		 * 
		 */		
		public static function fillReplayCollectionDefined():void{
			replayCollectionDefined.removeAll();
			var counter:int = 0;
			for each (var asd in replayCollection[0]){
				var o:Object={gameID:asd, date:replayCollection[1][counter],participants:replayCollection[2][counter],played:replayCollection[3][counter]};
				replayCollectionDefined.addItem(o);
				counter++;
				app.replayPanel.visible=true;
			}
		}
		
		/**
		 * Button Quit Handler 
		 * gameState wird auf login gesetzt Spieler wird vom Tisch genommen
		 * und aus User sowie Playerlist entfernt
		 */		
		public static function quit():void{
			if(app.currentState=="game"){
				app.consumerTable.unsubscribe();
				app.consumerGameState.unsubscribe();
				app.consumerMessage.unsubscribe()
				app.facade.quitGame(user.name);
				if(table.playersNames[table.activePlayerIndex]==user.name){
					app.facade.doAction("COMMAND_FOLD",0);
				}
				app.playerlist.removePlayer(user.name);
				app.userlist.removeUser(user.name);
				app.currentState="login";
			} else {
				app.consumerTable.unsubscribe();
				app.consumerGameState.unsubscribe();
				app.consumerMessage.unsubscribe()
				app.playerlist.removePlayer(user.name);
				app.userlist.removeUser(user.name);
				app.currentState="login";
				app.game
			}
		}
	}
}